import React from 'react';
import Taro from '@tarojs/taro';

import {connect} from 'react-redux';
import * as T from './types';
import actions from './actions';
import {store2Props} from './selectors';
import {
  GAME_SHARE_TITLE,
  CODE_SUCCESS,
  OSS_PATH_PREFIX,
  NAVBAR_TITLE,
  OSS_BASE_PATH_PREFIX,
  GAME_RPICE_TYPE,
  PRODUCT_STATUS,
  GAME_PRICE_INFO,
  SECONDS_FORMAT,
  CODE_COIN_INSUFFICIENT,
} from './constant';
import moment from 'dayjs';
import {View, Image, ScrollView} from '@tarojs/components';
import PageLoading from '../../common/PageLoading';
import './index.less';
import classNames from 'classnames';
import ExchangeModal from './components/ExchangeModal/ExchangeModal';
import MemberModal from './components/MemberModal/MemberModal';
import ExchangeDetailModal from './components/ExchangeDetailModal/ExchangeDetailModal';
import ExchangeResultModal from './components/ExchangeResultModal/ExchangeResultModal';
import CustomScrollView from '@/common/scrollview';

actions().actions.loadReducer();

// @ts-ignore
@connect<Partial<T.IProps>, any>(store2Props, actions)
export default class GoldCoinsExchangePa extends React.Component<Partial<T.IProps>, any> {
  // 使用state值
  constructor(props) {
    super(props);
    this.state = {
      query: {},
      pics: {
        jindou: OSS_PATH_PREFIX + '/jindou.png',
        exchangeQuestion: OSS_PATH_PREFIX + '/exchangeQuestionIcon.png',
        emptyIcon: OSS_BASE_PATH_PREFIX + '/emptyGrey.png',
        gameShareIcon: OSS_BASE_PATH_PREFIX + '/gameShareIcon.png', // 分享至朋友圈
        gameShareThum: OSS_BASE_PATH_PREFIX + '/gameShareThum.png', // 分享缩略图
      },
      navbarSettings: {
        navBarHeight: 0, // 导航栏高度
        menuRight: 0, // 胶囊距右方间距（方保持左、右间距一致）
        menuTop: 0, // 胶囊距底部间距（保持底部间距一致）
        menuHeight: 0, // 胶囊高度（自定义内容可与胶囊高度保证一致）
      },
      empty: {
        text: '暂无数据',
      },
      loading: {
        status: false,
        text: '',
        style: {
          border: '8rpx solid #ccc',
        },
        textStyle: {
          color: '#ccc',
        },
      },
      refresherTriggered: false,

      // 模态框显示
      modal: {
        type: '', // 多个模态框
        visible: false,
        item: null,
      },
      imageError: {},
    };
  }

  componentDidShow() {
    this.handleGetRouterParams(); // 获取路由参数
    this.props.actions.init();
  }

  componentDidMount(): void {
    this.getNavHeight();
  }

  /**
   * 获取路由参数
   */
  handleGetRouterParams = () => {
    let params = Taro.getCurrentInstance()?.router?.params;
    // 收藏进来的就直接去首页
    if (params.favorite) {
      Taro.redirectTo({
        url: '/pages/package-I/home/index',
      });
      return;
    }
    this.handleQuery();
  };

  componentWillReceiveProps(nextProps: Readonly<Partial<T.IProps>>, nextContext: any): void {
    if (nextProps.main.status.exchanging === false && this.props.main.status.exchanging == true) {
      if (nextProps.main.response.exchange == CODE_SUCCESS) {
        this.handleLoadUserInfo(); //查询用户信息
        this.handleQueryExchanges({
          total: 0,
          pageNum: 0,
        });
        let prizeType = nextProps.main.exchangeItem.prizeType;
        let label = '';
        if (prizeType >= 0) {
          label = GAME_PRICE_INFO[prizeType].title;
        }
        console.log('index.tsx handleSuccess label', label);
        Taro.showToast({
          title: label ? '兑换成功,' + label : '兑换成功!',
          icon: 'none',
        });
      } else if (nextProps.main.response.exchange == CODE_COIN_INSUFFICIENT) {
        Taro.showToast({
          title: '魔力豆不足,快去玩游戏吧~',
          icon: 'none',
        });
      } else {
        Taro.showToast({
          title: nextProps.main.codeMessage || '操作失败',
          icon: 'none',
        });
      }
    }

    if (nextProps.main.status.loadingExchange === false && this.props.main.status.loadingExchange == true) {
      this.setState({
        refresherTriggered: false,
      });
    }
  }

  /**
   * 获取navbar高度
   */
  getNavHeight() {
    var sysinfo = Taro.getSystemInfoSync();
    const menuButtonInfo = Taro.getMenuButtonBoundingClientRect();
    let navBarHeight = sysinfo.statusBarHeight + 44;
    let menuRight = sysinfo.screenWidth - menuButtonInfo.right;
    let menuTop = menuButtonInfo.top;
    let menuHeight = menuButtonInfo.height;
    this.setState({
      navbarSettings: {
        ...this.state.navbarSettings,
        navBarHeight, // 导航栏高度
        menuHeight,
        menuTop,
      },
    });
  }

  /**
   * 查询数据
   */
  handleQuery = () => {
    this.handleLoadUserInfo();
    this.handleQueryExchanges({});
  };

  /**
   * 查询用户基本信息
   */
  handleLoadUserInfo = () => {
    let params = {};
    this.props.actions.action.loadUserInfo(params);
  };

  /**
   * 查询兑换列表
   */
  handleQueryExchanges = (payload) => {
    const {
      main: {page},
    } = this.props;

    let params = {
      ...page,
      ...payload,
    };
    this.props.actions.action.loadExchangeItems(params);
  };

  componentWillUnmount() {
    this.props.actions.clean();
  }

  render() {
    if (!this.props.main) return null;
    let {
      main: {isLoading},
    } = this.props;
    console.log(isLoading);

    return (
      <View className="pageGoldCoinsExchangePa">
        {this.renderNavBar()}
        {this.renderContent()}
        {this.renderExchangeModal()}
        {this.renderMemberModal()}
        {this.renderExchangeDetailModal()}
        {this.renderExchangeResultModal()}
      </View>
    );
  }

  /**
   * 渲染基本信息
   */
  renderNavBar() {
    const {
      main: {userInfo},
    } = this.props;
    const {
      pics: {jindou, exchangeQuestion},
      navbarSettings: {navBarHeight, menuHeight, menuTop},
    } = this.state;
    let detailed = `魔力豆明细`;
    let extraDetailed = '>>';
    return (
      <View className="header">
        <View className="navbar" style={{height: navBarHeight}}>
          <View style={{height: menuHeight, top: menuTop}} className="navBarContent">
            <View className="at-icon at-icon-chevron-left" onClick={this.handleNavBack}></View>
            <View className="navTitle" style={{fontSize: '36rpx'}}>
              {NAVBAR_TITLE}
            </View>
          </View>
        </View>
        <View className="exchangeInfo">
          <View className="info">
            <Image src={jindou} className="jindou" />
            <View className="goldCoins">{userInfo.magicBean}</View>
            <View className="infoExtra" onClick={this.handleDetailedQuery}>
              {detailed}&nbsp;{extraDetailed}
            </View>
          </View>
          <View className="illustrate" onClick={this.handleExchangeQuestion}>
            <Image src={exchangeQuestion} className="questionIcon" />
            <View className="illustrateExtra">兑换说明</View>
          </View>
        </View>
      </View>
    );
  }

  /**
   * 点击兑换说明弹框
   */
  handleExchangeQuestion = () => {
    this.handleModalShowAndHide('exchangeDetail', true);
  };

  /**
   * 点击返回
   */
  handleNavBack = () => {
    Taro.navigateBack();
  };

  /**
   * 魔力豆明细页面
   */
  handleDetailedQuery = () => {
    Taro.navigateTo({
      url: '/pages/package-I/goldCoinsDetail/index',
    });
  };

  /**
   * 渲染列表
   * @returns
   */
  renderContent() {
    const {
      main: {
        status: {loadingExchange},
        exchangeItems,
      },
    } = this.props;
    console.log('index.tsx renderContent loadingExchange=', loadingExchange);
    return (
      <View className="exchangeContent">
        <View>魔力豆兑换</View>
        {this.renderList()}
      </View>
    );
  }

  /**
   * 渲染列表
   */
  renderList() {
    const {
      main: {
        exchangeItems,
        status: {loadingExchange},
      },
    } = this.props;
    const {pics, refresherTriggered} = this.state;

    console.log('index.tsx exchangeItems', exchangeItems);

    return (
      <CustomScrollView
        scrollY
        className="scrollViewContent"
        scrollWithAnimation
        onRefresherRefresh={this.handleRreshList}
        onScrollToLower={this.handleScrollLower}
        refresherEnabled
        refresherTriggered={refresherTriggered}
      >
        {exchangeItems.length > 0 ? (
          <View className="exchangeList">
            {exchangeItems.map((i: any, index: number) => (
              <View key={'exchange' + index} className="at-row exchangeItem">
                <View className="at-col at-col-3 left">
                  <View className="leftThum">
                    <Image
                      src={i.img || GAME_PRICE_INFO[Number(i.prizeType)].errorImage}
                      className="typeIcon"
                      onError={(e) =>
                        this.handleImageError(e, index, {
                          propName: 'exchangeItems',
                          imageState: 'img',
                        })
                      }
                    />
                  </View>
                </View>
                <View className="at-col at-col-6 middle">
                  <View className="typeName">{i.name}</View>
                  {(i.prizeType == GAME_RPICE_TYPE['ticket'] || i.prizeType == GAME_RPICE_TYPE['prop']) && i.endTime ? (
                    <View className="typeEndTime"> {'有效期至' + moment(i.endTime).format(SECONDS_FORMAT)}</View>
                  ) : (
                    <View className="typeEndTime"></View>
                  )}

                  <View className="typeExchange">
                    <Image src={pics.jindou} className="jindouIcon" />
                    <View className="exchangeNum">{i.magicBean}</View>
                  </View>
                </View>
                <View className="at-col at-col-3 right">
                  <View
                    onClick={() => this.handleExchangeModalShow(i)}
                    className={classNames(
                      i.status == PRODUCT_STATUS['pushed'] ? 'exchangeOperate' : 'exchangeOperateGet',
                      'exchangeDefault',
                    )}
                  >
                    {i.status == PRODUCT_STATUS['pushed'] ? '立即兑换' : '已下架'}
                  </View>
                </View>
              </View>
            ))}
          </View>
        ) : (
          this.renderEmptyContent()
        )}
      </CustomScrollView>
    );
  }

  /**
   * 点击立即兑换处理，已获得则不处理
   */
  handleExchangeModalShow = (item) => {
    const {
      main: {userInfo},
    } = this.props;

    if (item.status == PRODUCT_STATUS['withdraw']) {
      return;
    } else {
      // 判断是否是会员，如果是才可以弹兑换弹框，不是会员则提示去开会员
      if (userInfo.accountType) {
        this.handleModalShowAndHide('exchange', true, item);
      } else {
        this.handleModalShowAndHide('member', true);
      }
    }
  };

  /**
   * 图片加载错误
   * @param e
   * @param index
   */
  handleImageError = (e, index, item) => {
    const {main} = this.props;
    const {propName, imageState} = item;
    let {imageError} = this.state;
    if (imageError[propName]) {
      imageError[propName] = imageError[propName].concat([index]);
    } else {
      imageError[propName] = [index];
    }
    let result = JSON.parse(JSON.stringify(main[propName]));
    let currentImage = imageError[propName];
    let ids = currentImage;
    ids.map((i) => {
      result[i] = {
        ...result[i],
        [imageState]: GAME_PRICE_INFO[Number(result[i].prizeType)].errorImage,
      };
    });

    this.props.actions.action.commonChange('main.' + propName, result);
  };

  /**
   * 模态框的弹出和隐藏
   */
  handleModalShowAndHide = (type, visible, item = null) => {
    this.setState({
      modal: {
        ...this.state.modal,
        type: visible ? type : '',
        visible,
        item,
      },
    });
  };

  /**
   * 下拉刷新
   */
  handleRreshList = () => {
    console.log('index.tsx handleRreshList 下拉刷新');
    const {
      main: {
        page: {pageSize},
      },
    } = this.props;

    const {refresherTriggered} = this.state;
    if (refresherTriggered) return;

    this.setState({
      refresherTriggered: true,
    });

    this.handleQueryExchanges({
      pageSize,
      pageNum: 0,
      total: 0,
    });
  };

  /**
   * 滚动到底部（没有分页）
   */
  handleScrollLower = () => {
    const {
      main: {page, exchangeItems},
    } = this.props;

    if (page.pageNum > 0 && exchangeItems.length == page.total) {
      return;
    }
    let params = {
      ...page,
      pageNum: page.pageNum + 1,
    };
    // this.handleQueryExchanges(params);
  };

  /**
   * 渲染加载效果
   * @returns
   */
  renderLoadingContent() {
    const {
      loading: {status, text, style, textStyle},
    } = this.state;
    return (
      <View className="loadingContent">
        <PageLoading style={style} textStyle={textStyle} />
      </View>
    );
  }

  /**
   * 渲染空内容
   * @returns
   */
  renderEmptyContent() {
    const {
      pics: {emptyIcon},
      empty: {text},
    } = this.state;

    return (
      <View className="emptyContent">
        <Image src={emptyIcon} className="emptyIcon" />
        <View className="emptyExtraTitle">{text}</View>
      </View>
    );
  }

  /**
   * 渲染兑换模态框
   */
  renderExchangeModal() {
    const {
      modal: {visible, type, item},
      navbarSettings,
    } = this.state;

    return (
      <ExchangeModal
        visible={visible && type == 'exchange'}
        item={item}
        navbarSettings={navbarSettings}
        onConfirm={this.handleConfrimExchange}
        onCancel={(item) => this.handleModalShowAndHide('', false, item)}
      />
    );
  }

  /**
   * 去获取
   */
  handleTask = () => {
    this.handleModalShowAndHide('', false);
    Taro.navigateTo({
      url: '/pages/package-I/goldCoinsIndex/index',
    });
  };

  /**
   * 确认兑换
   */
  handleConfrimExchange = (item) => {
    console.log('index.tsx handleConfirmExchange item', item);
    this.handleModalShowAndHide('', false, item); // 关闭模态框

    // 编辑参数
    let params = {
      target: item,
    };
    this.props.actions.action.exchangeItem(params);
  };

  /**
   * 渲染会员弹框
   */
  renderMemberModal() {
    const {
      modal: {visible, type},
      navbarSettings,
    } = this.state;

    return (
      <MemberModal
        navbarSettings={navbarSettings}
        visible={visible && type == 'member'}
        onCancel={() => this.handleModalShowAndHide('', false)}
        onActivate={() => this.handleActivateMember()}
      />
    );
  }

  /**
   * 确定开通会员
   */
  handleActivateMember = () => {
    this.handleModalShowAndHide('', false); // 关闭模态框
    // 跳转到开通会员界面
    Taro.redirectTo({
      url: '/pages/package-A/memberOpen/index',
    });
  };

  /**
   * 渲染兑换说明模态框
   * @returns
   */
  renderExchangeDetailModal() {
    const {
      modal: {visible, type},
      navbarSettings,
    } = this.state;

    return (
      <ExchangeDetailModal
        navbarSettings={navbarSettings}
        visible={visible && type == 'exchangeDetail'}
        onCancel={() => this.handleModalShowAndHide('', false)}
      />
    );
  }

  /**
   * 兑换结果模态框
   * @returns
   */
  renderExchangeResultModal() {
    const {
      modal: {visible, type},
      navbarSettings,
    } = this.state;

    return (
      <ExchangeResultModal
        navbarSettings={navbarSettings}
        visible={visible && type == 'exchangeResult'}
        onCancel={() => this.handleModalShowAndHide('', false)}
        onTask={this.handleTask}
      />
    );
  }

  /**
   * 收藏
   * @param res
   * @returns
   */
  onAddToFavorites(res) {
    const {
      pics: {gameShareIcon},
    } = this.state;

    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target);
    }
    return {
      title: GAME_SHARE_TITLE,
      imageUrl: gameShareIcon,
      query: 'favorite=true',
    };
  }
}
